<template>
  <div class="options-manager">
    <div
      v-for="i in count"
      :key="i"
      class="options-manager-line">
      <span class="options-manager-id">{{ toChar(i - 1) }}</span>
      <mu-text-field v-model="options[i - 1]" class="options-manager-content"></mu-text-field>
      <mu-button color="primary" @click="setAnswer(i - 1)">选为答案</mu-button>
      <mu-button color="error" @click="removeOption(i - 1)">删除</mu-button>
    </div>
    <div class="options-manager-line">
      <span class="options-manager-id">+</span>
      <mu-button color="success" @click="addOption()">添加一条选项</mu-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OptionsManager',
  props: {
    value: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      options: []
    }
  },
  computed: {
    count() {
      return this.options.length
    }
  },
  watch: {
    value() {
      this.options = this.value
    },
    options() {
      this.$emit('input', this.options)
    }
  },
  created() {
    this.options = this.value
  },
  methods: {
    refresh() {
      const options = []
      for (let i = 0; i < 4; i++) {
        options.push('')
      }
      this.options = options
    },
    toChar(i) {
      return String.fromCharCode(65 + i)
    },
    removeOption(i) {
      this.options.splice(i, 1)
    },
    addOption() {
      this.options.push('')
    },
    setAnswer(i) {
      this.$emit('choose', i)
      const answer = String.fromCharCode(65 + i)
      this.$emit('update:answer', answer)
    }
  }
}
</script>

<style lang="scss">
.options-manager {
  flex-grow: 1;
}
.options-manager-line {
  display: flex;
  flex-direction: row;
  height: 60px;
  align-items: baseline;
}
.options-manager-id {
  width: 30px;
  font-size: 1.2em;
}
.options-manager-content {
  flex-grow: 1;
}
</style>
